package com.sky.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/admin/category")
@RestController
public class CategoryController {
    @Autowired
    CategoryMapper categoryMapper;
    @PostMapping
    public Result saveCategory(@RequestBody Category category){

               categoryMapper.save(category);
               return Result.success();
    }
    @PutMapping
    public  Result update(@RequestBody Category category){
        categoryMapper.update(category);
        return Result.success();
    }
 @GetMapping("/page")
    public Result page(CategoryPageQueryDTO categoryPageQueryDTO){
     int page = categoryPageQueryDTO.getPage();
     int pageSize = categoryPageQueryDTO.getPageSize();
     String name = categoryPageQueryDTO.getName();
     Integer type = categoryPageQueryDTO.getType();
     PageHelper.startPage(page,pageSize);
     Page page1 = (Page)categoryMapper.page(name, type);
     long total = page1.getTotal();
     List result = page1.getResult();
     return Result.success(new PageResult(total,result));
 }
 @PostMapping("/status/{status}")
    public  Result status(@PathVariable Integer status,Long id){
        Category category=new Category();
        category.setStatus(status);
        category.setId(id);
        categoryMapper.update(category);
        return Result.success();
 }
 @Autowired
 private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;



 @DeleteMapping
    public Result delete(Integer id){

     Integer i = dishMapper.selectCountById(id);
     if (i>0){
         throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
     }
     Integer j = setmealMapper.selectCountById(id);

     if (j>0){
         throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
     }
     categoryMapper.delete(id);
        return Result.success();
 }
 @GetMapping("/list")
    public Result list(Integer type){
        return Result.success(categoryMapper.getList(type));
 }

}
